package com.yuxinmuyu.sports_management.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuxinmuyu.sports_management.bean.entiy.SportsProject;
import com.yuxinmuyu.sports_management.bean.entiy.SportsYear;
import com.yuxinmuyu.sports_management.bean.request.GetSportsProjectRequest;
import com.yuxinmuyu.sports_management.bean.request.PageRequest;
import com.yuxinmuyu.sports_management.bean.response.SportsInfoResponse;
import com.yuxinmuyu.sports_management.exception.BusinessException;
import com.yuxinmuyu.sports_management.mapper.SportsYearMapper;
import com.yuxinmuyu.sports_management.service.SportsYearService;
import com.yuxinmuyu.sports_management.utils.UserUtil;
import com.yuxinmuyu.sports_management.utils.Utility;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SportsYearServiceImpl implements SportsYearService {
    @Resource
    SportsYearMapper sportsYearMapper;

    @Override
    public Page<SportsYear> getSportsYear(PageRequest request) {
        Page<SportsYear> page = new Page<>(request.getCurrentPage(),request.getPageSize());
        List<SportsYear> list= sportsYearMapper.selectList(null);
        list=list.stream().
                sorted(Comparator.comparingInt(SportsYear::getId).reversed()).collect(Collectors.toList());
        //手动分页
        Utility.getPage(page,list);
        return page;
    }

    @Override
    public void addSportsYear(SportsYear sportsYear) {
        SportsYear year = sportsYearMapper.selectById(sportsYear.getId());
        if (Objects.nonNull(year)){
            throw new BusinessException("已经存在该信息！");
        }
        sportsYear.setOperator(UserUtil.getUserName());
        int n = sportsYearMapper.insert(sportsYear);
        if(n==0){
            throw new BusinessException("添加失败！");
        }

    }

    @Override
    public Page<SportsInfoResponse> selectPage(GetSportsProjectRequest request) {
        Page<SportsInfoResponse>page=new Page<>(request.getCurrentPage(),request.getPageSize());
        page=sportsYearMapper.selectPageList(page,request.getYearTermID(),request.getSportsName());
        page.getRecords().forEach(dto->{
            dto.setFlag(sportsYearMapper.getflag(dto.getSportsID(),dto.getYearTermID(),UserUtil.getUserId()));
        });
        return page;
    }
}
